package com.pfzy.lib.sdk.utils.zip;

import android.text.TextUtils;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ZipChannelUtils {
    /**
     * 获取频道文件名
     *
     * @param apkFile
     * @return
     */
    public static String getChannelFileName(File apkFile) {
        try {
            String channelFilePath = getExpectedChannelFilePath(apkFile);
            if (!TextUtils.isEmpty(channelFilePath) && channelFilePath.contains("caocaozhuanche_channel_")) {
                return channelFilePath.substring(9, channelFilePath.length());
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取预期的通道文件路径
     * @param apkFile
     * @return
     */
    private static String getExpectedChannelFilePath(File apkFile) {
        RandomAccessFile randomAccessFile = null;
        DataSource dataSource;
        long eocdAndOffsetInFile;
        try {
            randomAccessFile = new RandomAccessFile(apkFile, "r");
            dataSource = DataSources.asDataSource(randomAccessFile, 0L, randomAccessFile.length());
            eocdAndOffsetInFile = ZipUtils.findZipEndOfCentralDirectory(dataSource);
            if (eocdAndOffsetInFile != 0) {
                ByteBuffer byteBuffer = dataSource.getByteBuffer((eocdAndOffsetInFile - 92) - 100, 192);
                byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
                for (int expectedIndex = 100; expectedIndex >= 0; expectedIndex--) {
                    if (byteBuffer.getInt(expectedIndex) == 33639248) {
                        byteBuffer.position(expectedIndex);
                        CentralDirectoryRecord cdRecord = CentralDirectoryRecord.getRecord(byteBuffer);
                        if (cdRecord != null) {
                            if (randomAccessFile != null) {
                                randomAccessFile.close();
                            }
                            return cdRecord.getName();
                        }
                    }
                }
            }

            if (randomAccessFile != null) {
                randomAccessFile.close();
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } catch (Throwable th) {
            throw th;
        }
    }
}
